<template>
    <div>
        <el-dialog
                title="添加商品"
                :visible.sync="addDialogVisible"
                width="65%"
                @close="addDialogClosed"
                :close-on-click-modal=false>
            <!--内容主体区-->
            <el-steps :active="active" finish-status="success" simple>
                <el-step title="基本信息"></el-step>
                <el-step title="商品描述"></el-step>
                <el-step title="规格参数"></el-step>
                <el-step title="SkU属性"></el-step>
            </el-steps>
            <!--基本信息-->
            <el-form :model="addForm" label-width="70px" ref="addFormRef" class="base-info">
                <div  v-if="active === 0">

                    <el-form-item label="商品类目" prop="cid">
                        <!--商品分类-->
                        <el-cascader
                                ref="myRef"
                                style="width: 100%"
                                v-model="addForm.cid"
                                :options="categories"
                                @change="changeCascader"
                                :props="props"
                                placeholder="请选择商品类目"
                                clearable>
                        </el-cascader>
                    </el-form-item>
                    <!--所属品牌-->
                    <el-form-item label="所属品牌" prop="image">
                        <el-select style="width: 100%" v-model="addForm.bid" clearable placeholder="请选择所属品牌">
                            <el-option
                                    v-for="item in brands"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品名称" prop="title">
                        <el-input v-model="addForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="子标题" prop="subTitle">
                        <el-input v-model="addForm.subTitle"></el-input>
                    </el-form-item>

                </div>
                <!--商品描述-->
                <div class="goods-desc" v-if="active === 1">
                    <el-form-item label="包装清单" prop="packingList">
                        <el-input v-model="addForm.packingList"></el-input>
                    </el-form-item>
                    <el-form-item label="售后服务" prop="afterService">
                        <el-input v-model="addForm.afterService"></el-input>
                    </el-form-item>
                    <el-form-item label="商品描述" prop="description">
                        <quill-editor ref="myQuillEditor" v-model="addForm.description" :options="editorOption"/>

                        <el-upload

                                drag
                                multiple
                                class="quill-upload"
                                :on-success="quillSuccess"
                                action="http://upload.gker.com/upload/upload"
                        >
<!--                             <el-button size="small" type="primary">点击上传</el-button>-->
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">
                                将文件拖到此处，或
                                <em>点击上传</em>
                            </div>
                        </el-upload>
                    </el-form-item>
                </div>

                <!--通用规格参数-->
                <div class="category" v-if="active === 2">
                    <H3 style="margin-left: 60px">通用规格参数</H3>
                    <el-form-item :label="item.name" :prop="item.name" v-for="(item,index) in generalSpecs" label-width="140px">
                        <el-input v-model="addForm.generalParams[index]">
                            <template slot="append" v-if="item.unit">{{item.unit}}</template>
                        </el-input>
                    </el-form-item>
                </div>
                <!--SkU属性-->
                <div class="sku-param" v-if="active === 3">
                    <!--<el-table
                            ref="multipleTable"
                            :data="resultTable"
                            tooltip-effect="dark"
                            style="width: 100%"
                            @selection-change="handleSelectionChange">
                        &lt;!&ndash;选择器&ndash;&gt;
                        <el-table-column
                                type="selection"
                                width="55">
                        </el-table-column>


                        <el-table-column v-for="(key,index) in Object.keys(resultTable[0])" :key="Math.random(index)" :label="key" :prop="key" align="center" show-overflow-tooltip>
                        </el-table-column>

&lt;!&ndash;                        &lt;!&ndash;这边是特有规格的列&ndash;&gt;&ndash;&gt;
&lt;!&ndash;                        <el-table-column&ndash;&gt;
&lt;!&ndash;                                :label=item.name&ndash;&gt;

&lt;!&ndash;                                width="120"&ndash;&gt;
&lt;!&ndash;                                v-for="(item,index) in specialSpecs"&ndash;&gt;
&lt;!&ndash;                        >&ndash;&gt;

&lt;!&ndash;                        </el-table-column>&ndash;&gt;





                        <el-table-column
                                label="价格"
                                width="120">
                            <template slot-scope="scope">
                                <el-input  placeholder="请输入内容"></el-input>
                            </template>
                        </el-table-column>

                        <el-table-column
                                label="库存"
                                width="120">
                            <el-input  placeholder="请输入内容"></el-input>
                        </el-table-column>

                    </el-table>-->
                    <div>
                        <SkuForm
                                :source-attribute="sourceAttribute"
                                :attribute.sync="attribute"
                                :sku.sync="sku"
                                :structure="structure"
                                :theme="theme"
                        >
                        <template #image="slotProps">
                            <div class="image-upload-container">
                                <el-image v-if="slotProps.row.image" :src="slotProps.row.image" :preview-src-list="[slotProps.row.image]" fit="cover" title="点击预览" />
                                <el-upload :show-file-list="false" action="http://upload.gker.com/upload/upload"  name="file"  :on-success="res => imageUpload(res, slotProps)" class="images-upload">
                                    <el-button size="small" icon="el-icon-upload2">{{ slotProps.row.image ? '重新上传' : '上传图片' }}</el-button>
                                </el-upload>
                                <el-button v-if="slotProps.row.image" size="small" icon="el-icon-delete" @click="imageRemove(slotProps)" />
                            </div>
                        </template>
                        </SkuForm>
<!--                        <el-row type="flex" :gutter="20">
                            <el-col>
                                <el-divider content-position="left">attribute 数据</el-divider>
                                <pre><code>{{ attribute }}</code></pre>
                            </el-col>
                            <el-col>
                                <el-divider content-position="left">sku 数据</el-divider>
                                <pre><code>{{ sku }}</code></pre>
                            </el-col>
                        </el-row>-->
                    </div>

                </div>

            </el-form>
            <!--底部-->
            <span slot="footer" class="dialog-footer">
            <el-button style="margin-top: 12px;" @click="prev" :disabled="active===0">上一步</el-button>
            <el-button style="margin-top: 12px;" @click="next" :disabled="active===3">下一步</el-button>
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addGoodsHandle" :disabled="active!==3">确 定</el-button>
            </span>


        </el-dialog>
    </div>
</template>

<script>
    import 'quill/dist/quill.snow.css'
    import { quillEditor, Quill } from 'vue-quill-editor'
    import { container, ImageExtend, QuillWatch } from 'quill-image-extend-module'
    Quill.register('modules/ImageExtend', ImageExtend)
    export default {
        name: "AddGoods",
        components: { quillEditor },
        props: ['categories', 'brands'],
        data() {
            return {
                addDialogVisible: false,
                active: 0,
                props: {
                    label: 'name',
                    children: 'children',
                    value: 'id',
                    emitPath: false
                },
                skuList:[],
                addForm: {
                    cid1:'',
                    cid: '',
                    bid: '',
                    title: '',
                    subTitle: '',
                    packingList: '',
                    afterService: '',
                    description: '',
                    generalParams:[]
                },
                generalSpecs: [], // 通用规格参数的模板
                specialSpecs: [], // 特有规格参数模板
                generalSpecParam: [],
                finalGeneralSpecParam:{},
                specialSpecParam: [],
                finalSpecialSpecs:{},


                //skuForm
                sourceAttribute: [],
                attribute: [],
                sku: [],
                theme: 2,
                structure: [
                    {
                        name: 'price',
                        type: 'input',
                        label: '价格',
                        batch: false
                    },
                    {
                        name: 'stock',
                        type: 'input',
                        label: '库存',
                        batch: false
                    },
                    {
                        name: 'image',
                        type: 'slot',
                        label: '图片',
                        required: true,
                        batch: false
                    }
                ],
                // 富文本框参数设置
                editorOption: {
                    modules: {
                        ImageExtend: {
                            loading: true,
                            name: 'file',
                            action: 'http://upload.gker.com/upload/upload',
                            response: (res) => {
                                return res.data.data.fileName
                            }
                        },
                        toolbar: {
                            container: container,
                            // handlers: {
                            //     'image': function () {
                            //         QuillWatch.emit(this.quill.id)
                            //     }
                            // }

                            handlers: {
                                // 重写点击组件上的图片按钮要执行的代码
                                'image': function (value) {
                                    document.querySelector('.quill-upload .el-icon-upload').click()
                                }

                            }
                        }
                    },

                    //---------------------------

                    // handleSuccessQuill(res) {
                    //     // 获取富文本组件实例
                    //     const quill = this.$refs.myQuillEditor.quill
                    //     // 如果上传成功
                    //     if (res) {
                    //         // 获取光标所在位置
                    //         const length = quill.getSelection().index
                    //         // 插入图片，res为服务器返回的图片链接地址
                    //         quill.insertEmbed(length, 'image', res.data.path)
                    //         // 调整光标到最后
                    //         quill.setSelection(length + 1)
                    //     } else {
                    //         // 提示信息，需引入Message
                    //         this.$message.error('图片插入失败')
                    //     }
                    // },


                    //---------------------------




                }
            }
        },
        methods: {
            //---------------------------------------
            imageUpload(res, data) {
                let imagePath = res.data.url
                console.log(imagePath)
                data.row.image = imagePath
                this.$message.success('图片上传成功')
                this.$refs.skuForm.validateFieldByRows(data.$index, 'image', () => {})
            },
            imageRemove(data) {
                data.row.image = ''
            },
            // 上传成功
            uploadSuccess(res) {
                var dt = res.result
                let quill = this.$refs.myQuillEditor.quill
                // 如果上传成功
                if (dt.meta.status === this.GLB.IMAGE_ADD_SUCCESS && dt.url !== null) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index
                    // 插入图片  dt.url为服务器返回的图片地址
                    quill.insertEmbed(length, 'image', this.glAPI + dt.url)
                    // 调整光标到最后
                    quill.setSelection(length + 1)
                } else {
                    this.$message.error('图片插入失败')
                }
                // loading加载隐藏
                this.quillUpdateImg = false
            },

//---------
            quillSuccess(response)
            {
                if (response) {
                    // 获取文本编辑器
                    const quill = this.$refs.myQuillEditor.quill
                    // 获取光标位置
                    const pos = quill.getSelection().index
                    // 插入图片到光标位置
                    quill.insertEmbed(pos, 'image', response.data.url)
                } else {
                    this.$essage.error('图片插入失败')
                }
            },
            //---------------------------------------


            showDialog()
            {
                this.addDialogVisible = true;
            },
            next() {
                if (this.active++ > 3) this.active = 0;
            },
            prev(){
                if (this.active>0) this.active--
            },
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
                this.addForm = {}
                this.active = 0
                this.attribute = []
                this.sku = []
                this.addDialogVisible = false;
            }
            ,
            changeCascader()
            {
                this.addForm.cid1 = this.$refs.myRef.getCheckedNodes()[0].parent.value
                this.$emit('getBrandByCid', this.$refs.myRef.getCheckedNodes()[0].value)
            },
            //通过cid获取通用和特有参数
            async getSpecsByCid(){
                const res = await this.$http.get("/item/spec/getParamsByCid/"+this.addForm.cid)
                res.data.data.forEach(item=>{
                    if (item.generic===true){
                        this.generalSpecs.push(item)
                    }else {
                        this.specialSpecs.push(item)
                        let obj = new Object();
                        obj.item = []
                        obj.name = item.name
                        this.sourceAttribute.push(obj)
                    }
                })
            },



            addGoodsHandle(){
                for (let i = 0; i < this.attribute.length; i++) {
                    for (let j = 0; j < this.specialSpecs.length; j++) {
                        if (this.attribute[i].name===this.specialSpecs[j].name){
                            let key = this.specialSpecs[j].id
                            this.finalSpecialSpecs[key] =this.attribute[i].item
                            break
                        }
                    }
                }

                //通用
                for (let j = 0; j <this.addForm.generalParams.length; j++) {
                    if (this.addForm.generalParams[j]!=null){
                        let key = this.generalSpecs[j].id
                        this.finalGeneralSpecParam[key] = this.addForm.generalParams[j]
                    }
                }

                //准备组装sku
                for (let i = 0; i < this.sku.length; i++) {
                    let skuObj = new Object()
                    //组装own_spec
                    //先转换数组
                    let skuArr = this.sku[i].sku.split(";")
                    this.sku[i].skuArr = skuArr
                    let indexesArr = []
                    let spec = new Object()
                    for (let j = 0; j < this.attribute.length; j++) {
                        for (let k = 0; k < this.specialSpecs.length; k++) {
                            if (this.attribute[j].name === this.specialSpecs[k].name){
                                let key = this.specialSpecs[k].id
                                spec[key] = this.sku[i].skuArr[j]
                                break
                            }
                        }
                        //组装indexes
                        for (let k = 0; k < this.attribute[j].item.length; k++) {

                            if (skuArr[j] === this.attribute[j].item[k]){
                                indexesArr.push(k)
                            }
                        }


                    }
                    skuObj.price = this.sku[i].price * 100
                    skuObj.images = this.sku[i].image
                    skuObj.stock = this.sku[i].stock
                    skuObj.indexes = indexesArr.join("_")
                    skuObj.ownSpec = JSON.stringify(spec)
                    skuObj.title = this.addForm.title
                    skuObj.enable = 1
                    //sku对象成组
                    this.skuList.push(skuObj)    //own_spec可算组装好了
                }

                let data = {
                    cid1:this.addForm.cid1,
                    cid2:this.addForm.cid,
                    brandId:this.addForm.bid,
                    title:this.addForm.title,
                    subTitle:this.addForm.subTitle,
                    spuDetail:{
                        description: this.addForm.description,
                        specialSpec: JSON.stringify(this.finalSpecialSpecs),
                        genericSpec: JSON.stringify(this.finalGeneralSpecParam),
                        packingList: this.addForm.packingList,
                        afterService: this.addForm.afterService,
                    },
                    skus:this.skuList
                }
                this.$http.post("/item/goods/saveGoods",data).then(res=>{
                    console.log(res)
                    if (res.data.code!=="200"){
                        this.$message.error("新增失败！")
                    }else {
                        this.$message.success("新增成功！")
                    }
                    this.addDialogClosed()
                    this.$emit("getGoodsList")
                })
            },


        },
        created() {
            this.$emit('')
            this.getSpecsByCid()
        },
        computed: {
            cid() {
                return this.addForm.cid
            }
        },
        watch:{
            // active(val){
            //     if (val===2){
            //         this.getSpecsByCid()
            //     }
            // }
            cid(){
                console.log(this.addForm.cid)
                this.getSpecsByCid()
    }
        }
    }
</script>

<style lang="less" scoped>
    .base-info{
        width: 800px;
        margin: 20px auto;
    }
    .quill-upload{
        display: none;
    }
</style>
